package com.zjmzxfzhl.modules.app.platform;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MailinaboxUserUtils {

    @Value("${mailinabox.email}")
    private  String adminEmail; //管理员邮箱
    @Value("${mailinabox.password}")
    private String adminPassword; // 管理员密码
    @Value("${mailinabox.serverHost}")
    private String serverHost;
    @Value("${listener.url}")
    private String url;

    /**
     * 新建邮箱 Mail-in-a-Box
     * @param email 邮箱地址
     * @param password 密码
     * @param privileges 身份 Enum:"admin",""
     * @return
     * @throws Exception
     */
    public String addUsers(String email,String password,String privileges)throws Exception{
        String url="https://"+serverHost+"/admin/mail/users/add";

        String user=adminEmail+":"+adminPassword;
        byte[] authEncBytes = Base64.encodeBase64(user.getBytes("utf-8"));
        String authStringEnc = new String(authEncBytes);

        //新建邮箱数据
        String data="email="+email+"&password="+password+"&privileges="+privileges;

        String result=post(url,authStringEnc,data,null);
        return result;
    }

    /**
     * 删除邮箱 Mail-in-a-Box
     * @param email 邮箱地址
     * @return
     * @throws Exception
     */
    public String addRemove(String email)throws Exception{
        String url="https://"+serverHost+"/admin/mail/users/remove";

        String user=adminEmail+":"+adminPassword;
        byte[] authEncBytes = Base64.encodeBase64(user.getBytes("utf-8"));
        String authStringEnc = new String(authEncBytes);

        //新建邮箱数据
        String data="email="+email;

        String result=post(url,authStringEnc,data,null);
        return result;
    }

    public HttpClient createSSLHttpClient() throws Exception {
        HttpClient httpclient = new DefaultHttpClient();

        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new javax.net.ssl.TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, ssf));

        return httpclient;

    }

    /**
     * POST请求
     * @param url URL
     * @param data 请求参数
     * @param authStringEnc 登录用户加密串
     * @return 返回结果
     */
    public String post(String url, String authStringEnc, String data, HttpClient httpClient) {
        Assert.hasText(url);
        String result = null;
        try {
            if (httpClient==null) {
                httpClient = createSSLHttpClient();
            }

            HttpPost httpPost = new HttpPost(url);

            httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
            httpPost.addHeader("Accept","application/x-www-form-urlencoded");
            httpPost.addHeader("Authorization","Basic " + authStringEnc);
            httpPost.setEntity(new StringEntity(data, "UTF-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity,"UTF-8");
            EntityUtils.consume(httpEntity);
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }
}
